package com.service;

import com.dao.RecordDao;
import com.dao.UserDao;
import com.datasource.DynamicDataSource;
import com.dto.BorrowBookDTO;
import com.dto.EmailLogDTO;
import com.dto.PwdDTO;
import com.dto.RecordDTO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.po.RecordPO;
import com.po.UserPO;
import com.util.MailUtils;
import com.util.RestException;
import com.util.UserLocal;
import com.vo.BookVO;
import com.vo.UserRecordBarVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author linyukun
 * @date 2022/7/11 19:14
 */
@Service
public class RecordServiceImpl {

    @Autowired
    private RecordDao recordDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private EmailLogServiceImpl emailLogServiceImpl;

    @Value("${max_renew_num}")
    private String maxRenewNum;



    public List<RecordPO> getRecordListByBookId(long bookId){
        return recordDao.getRecordListByBookId(bookId);

    }


     /**
       * 借书的逻辑
       * @author linyukun
       * @date 2022-07-19 9:30
     */
     @Transactional
    public Object borrowBook(BorrowBookDTO dto) {
        String borrowUserId = dto.getBorrowUserId();
        List<RecordDTO> borrowBooks = dto.getBorrowBooks();
        if(CollectionUtils.isEmpty(borrowBooks)){
            throw new RestException("请传递需要借阅的书籍");
        }
        if(StringUtils.isBlank(borrowUserId)){
            throw new RestException("请传递借书人");
        }
        UserPO userPO = userDao.getUserById(borrowUserId);
        if(ObjectUtils.isEmpty(userPO)){
            throw new RestException("找不到借书人");
        }
         Integer result = 0;
         synchronized (this){
            //region 判断是否已经超过可借阅的最大上限
            List<RecordPO> borrowedRecords = recordDao.getBorrowRecordByUserName(borrowUserId);
            if(!CollectionUtils.isEmpty(borrowedRecords) &&
                    ( borrowedRecords.size() +  borrowBooks.size() ) > userPO.getBorrowNum()){
                throw new RestException("您最大借阅的书籍数量是" + userPO.getBorrowNum() + "，目前您已借阅了" + borrowedRecords.size() + "本");
            }
            //endregion 判断是否已经超过可借阅的最大上限

            //region 判断这个库存是否已经外借了
            for(RecordDTO ele : borrowBooks){
                if(!CollectionUtils.isEmpty(recordDao.getBorrowRecordByBookStockId(ele.getBookStockId()))){
                    throw new RestException("条形码为：" + ele.getTicketNumber() + "已经被借出了，请重新选择");
                }
                //设置最大的续借次数
                ele.setMaxRenewNum(new Integer(maxRenewNum));
            }
            //endregion 判断这个库存是否已经外借了
            result = recordDao.batchInsertBorrowBook(borrowBooks,borrowUserId);
            //修改库存的状态
            if(result.intValue() > 0 ){
                borrowBooks.stream().forEach(ele -> {
                    recordDao.updateBookStrokStatusIsBorrow(ele.getBookStockId());
                });
            }
        }


        return result;
    }

    //根据用户名获取借阅信息
    public Object getRecordByUserName(BorrowBookDTO dto) {
         if(StringUtils.isBlank(dto.getBorrowUserName())){
             throw new RestException("请传递借阅人");
         }
         List<RecordPO> records = recordDao.getBorrowRecordByUserName(dto.getBorrowUserName());
        RecordPO result = null;
         if(!CollectionUtils.isEmpty(records)){
             for(RecordPO record :  records){
                 if(StringUtils.equals(record.getTicketNumber(),dto.getTicketNumber()) && "3".equals(record.getBookStockStatus())){
                     result = record;
                 }
             }
         }
         if(ObjectUtils.isEmpty(result)){
             throw new RestException("该用户尚无借阅的书籍信息");
         }
         return result;

    }


    //根据用户名获取借阅信息
    public Object getRecordByUserNameList(BorrowBookDTO dto) {
        if(StringUtils.isBlank(dto.getBorrowUserName())){
            throw new RestException("请传递借阅人");
        }
        List<RecordPO> records = recordDao.getBorrowRecordByUserNameList(dto);
//        RecordPO result = null;
//        if(!CollectionUtils.isEmpty(records)){
//            for(RecordPO record :  records){
//                if(StringUtils.equals(record.getTicketNumber(),dto.getTicketNumber()) && "3".equals(record.getBookStockStatus())){
//                    result = record;
//                }
//            }
//        }
        if(CollectionUtils.isEmpty(records)){
            throw new RestException("找不到数据");
        }
        return records;

    }

    //根据用户名获取借阅信息
    public PageInfo getAllRecordByUserName(BorrowBookDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo(recordDao.getAllRecordByUserName(dto));
    }

    //归还图书
    public Object backBook(BorrowBookDTO dto) {
        String borrowUserName = dto.getBorrowUserName();
        List<RecordDTO> borrowBooks = dto.getBorrowBooks();
        if(CollectionUtils.isEmpty(borrowBooks)){
            throw new RestException("请传递需要归还的书籍");
        }
        if(StringUtils.isBlank(borrowUserName)){
            throw new RestException("请传递归还人");
        }
        UserPO userPO = userDao.getUserByName(borrowUserName);
        if(ObjectUtils.isEmpty(userPO)){
            throw new RestException("找不到归还人");
        }
        Integer result = 0;
        synchronized(this){
            result = recordDao.batchBackBook(borrowBooks,borrowUserName);
        }



        return result;

    }

    public Object renewBooks(List<RecordDTO> recordDTOs) {
         if(CollectionUtils.isEmpty(recordDTOs)){
             throw new RestException("请传递书籍");
         }
        return recordDao.renewBooks(recordDTOs);
    }

    public Object getRecordHistoryList(BorrowBookDTO dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return new PageInfo(recordDao.getRecordHistoryList(dto));
    }


     /**
       * 获取用户的借阅记录的柱状图
       * @author linyukun
       * @date 2022-07-27 10:40
     */
    public Object getUserRecordBarData(BorrowBookDTO dto) {
        List<UserRecordBarVO> yearBar = recordDao.getUserRecordBarYear(dto);
        List<UserRecordBarVO> yearMonthBar = recordDao.getUserRecordBarYearDetail(dto);
        Map<String,Object> result = new HashMap<>();
        result.put("yearBar" , yearBar);
        result.put("yearMonthBar" , yearMonthBar);
        //拆分
        return result;
    }

    public List<BookVO>  getBorrowRanking(BorrowBookDTO dto) {
        return recordDao.getBorrowRanking(dto);
    }

    public Object emailNotification(RecordDTO dto) {
        if(ObjectUtils.isEmpty(dto.getId())){
            throw new RestException("数据不对");
        }
        PwdDTO pwdDto = new PwdDTO();
        pwdDto.setUserName(dto.getUserName());
        UserPO userPO = userServiceImpl.getUserByNameAll(pwdDto);
        if(StringUtils.isBlank(userPO.getEmail())){
            throw new RestException("该用户没有邮箱");
        }
        String content = "尊敬的用户您好，您尚有一本名为" + dto.getBookName() + "的数据已超过还书时间，请及时归还，图书管理系统。";
        String subject = "请及时还书";
        this.sendEmail(subject,content,userPO.getEmail());
        recordDao.updateRecordEmailNotification(dto);//修改数据

        // region 记录邮件日志
        EmailLogDTO emailLogDTO = new EmailLogDTO();
        emailLogDTO.setEmail(userPO.getEmail());
        emailLogDTO.setCreateUser(dto.getCreateUser());
        emailLogDTO.setContent(content);
        emailLogDTO.setSubject(subject);
        emailLogDTO.setUserName(dto.getUserName());

        emailLogServiceImpl.addEmailLog(emailLogDTO);
        // endregion 记录邮件日志
        return 1;
    }

    public void sendEmail(String subject,String content,String to){
        MailUtils.sendByAccountAndPwd(
                "smtp.exmail.qq.com",
                "linyukun@winshang.com",
                Arrays.asList(to),//asList之后不能进行新增删除操作 不然会报错的
                subject,
                content,
                "linyukun@winshang.com",
                "Linyk123456"
        );
    }
}
